package com.zhufei.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.zhufei.dao.HomePageImageDao;
import com.zhufei.dao.Paging;
import com.zhufei.dao.ZhuFeiUserInfoDao;

public class PicNewsServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public PicNewsServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String action = request.getParameter("action");
		if(action == null){
			
		}
		if(action.equals("add")){
			this.add(request,response);
		}
		if(action.equals("delete")){
			this.delete(request,response);
		}
		if(action.equals("manage")){
			this.manage(request,response);
		}
		
	}

	private void manage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HomePageImageDao picNewsDao = new HomePageImageDao();
		int picNewsCount = picNewsDao.getCountOfImages();
		ArrayList picNewsList = picNewsDao.getImages(0, picNewsCount);
		HttpSession session = request.getSession();
		session.setAttribute("picNewsList", picNewsList);
		Paging paging = new Paging();
		//取得page值
		String strPage = paging.strPage(request, "page");
		int current_Page = paging.current_Pages(strPage);
		//设置一页显示多少行数据
		int page_record = paging.setPage_record(10);
		//取得总页数
		int total_page = paging.getTotal_Pages(picNewsCount);
		//保存当前页数
		session.setAttribute("current_page", current_Page);
		//保存总页数
		session.setAttribute("total_page", total_page);
		session.setAttribute("page_record", page_record);
		response.sendRedirect("admin/managePictureNews.jsp");	
	}

	private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf8");
		String ID = request.getParameter("id");
		HomePageImageDao picNewsDao = new HomePageImageDao();
		boolean isSucc = picNewsDao.deleteImage(ID);
		if(isSucc){
			PrintWriter   out   =   response.getWriter(); 
			out.write( " <script   language=javascript> alert( '删除图片展示新闻成功！ ');window.location.href= 'PicNewsServlet?action=manage'; </script> "); 
			out.flush(); 
			out.close(); 
		}else{
			PrintWriter   out   =   response.getWriter(); 
			out.write( " <script   language=javascript> alert( '删除图片展示新闻失败！ ');window.location.href= 'PicNewsServlet?action=manage'; </script> "); 
			out.flush(); 
			out.close(); 		    
			}
	}

	private void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf8");
	   String title = null;
	   String newsID = null;
	   final long MAX_SIZE = 3 * 1024 * 1024;// 设置上传文件最大为 3M
	   // 允许上传的文件格式的列表
	   final String[] allowedExt = new String[] { "jpg", "jpeg", "gif", "png"};
	   // 设置字符编码为UTF-8, 这样支持汉字显示
	   response.setCharacterEncoding("UTF-8");

	   // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
	   DiskFileItemFactory dfif = new DiskFileItemFactory();
	   dfif.setSizeThreshold(4096);// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘
	   dfif.setRepository(new File(request.getRealPath("/")
	     + "ImagesUploadTemp"));// 设置存放临时文件的目录,web根目录下的ImagesUploadTemp目录

	   // 用以上工厂实例化上传组件
	   ServletFileUpload sfu = new ServletFileUpload(dfif);
	   // 设置最大上传尺寸
	   sfu.setSizeMax(MAX_SIZE);

	   PrintWriter out = response.getWriter();
	   // 从request得到 所有 上传域的列表
	   List fileList = null;
	   try {
	    fileList = sfu.parseRequest(request);
	   } catch (FileUploadException e) {// 处理文件尺寸过大异常
	    if (e instanceof SizeLimitExceededException) {
			out.write( " <script   language=javascript> alert( '文件尺寸过大！ ');window.location.href= 'admin/addPictureNews.jsp'; </script> "); 
			out.flush(); 
			out.close(); 
	     return;
	    }
	    e.printStackTrace();
	   }
	   // 没有文件上传
	   if (fileList == null || fileList.size() == 0) {
			out.write( " <script   language=javascript> alert( '请选择上传文件！ ');window.location.href= 'admin/addPictureNews.jsp'; </script> "); 
			out.flush(); 
			out.close(); 
	    return;
	   }
	   // 得到所有上传的文件
	   Iterator fileItr = fileList.iterator();
	   int i=0;
	   // 循环处理所有文件
	   while (fileItr.hasNext()) {
		   
	    FileItem fileItem = null;
	    String path = null;
	    long size = 0;
	    // 得到当前文件
	    fileItem = (FileItem) fileItr.next();
	    i++;
	    // 忽略简单form字段而不是上传域的文件域(<input type="text" />等)
	    if (fileItem == null || fileItem.isFormField()) {
	    	
			if(fileItem.getFieldName().equals("title")){
				title = new String(fileItem.getString().getBytes("iso8859-1"), "utf8");
				
			}
			if(fileItem.getFieldName().equals("newsID")){
				newsID = new String(fileItem.getString().getBytes("iso8859-1"), "utf8");
			}
					
	    }
	    //如果是文件才进行下一步操作
	    if(!fileItem.isFormField()){
	    // 得到文件的完整路径
	    path = fileItem.getName();
	    // 得到文件的大小
	    size = fileItem.getSize();
	    if ("".equals(path) || size == 0) {
			out.write( " <script   language=javascript> alert( '请选择上传文件！ ');window.location.href= 'admin/addPictureNews.jsp'; </script> "); 
			out.flush(); 
			out.close(); 
	     return;
	    }

	    // 得到去除路径的文件名
	    String t_name = path.substring(path.lastIndexOf("\\") + 1);
	    // 得到文件的扩展名(无扩展名时将得到全名)
	    String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
	    // 拒绝接受规定文件格式之外的文件类型
	    int allowFlag = 0;
	    int allowedExtCount = allowedExt.length;
	    for (; allowFlag < allowedExtCount; allowFlag++) {
	     if (allowedExt[allowFlag].equals(t_ext))
	      break;
	    }
	    if (allowFlag == allowedExtCount) {
			out.write( " <script   language=javascript> alert( '请上传图片格式文件！ ');window.location.href= 'admin/addPictureNews.jsp'; </script> "); 
			out.flush(); 
			out.close(); 
	     return;
	    }

	    long now = System.currentTimeMillis();
	    // 根据系统时间生成上传后保存的文件名
	    String prefix = String.valueOf(now);
	    // 保存的最终文件完整路径,保存在web根目录下的ImagesUploaded目录下
	    String u_name = request.getRealPath("/") + "NewsImages/"
	      + prefix + "." + t_ext;
	    try {
	     // 保存文件
	     fileItem.write(new File(u_name));
	     //写入数据库
	     //
		String saveName = "NewsImages/"
		      + prefix + "." + t_ext;
	     HomePageImageDao picNewsDao = new HomePageImageDao();
	     boolean isSucc =  picNewsDao.insertImage(title, saveName, newsID);
	     
		if(isSucc){
			out.write( " <script   language=javascript> alert( '添加图片展示新闻成功！ ');window.location.href= 'PicNewsServlet?action=manage'; </script> "); 
			out.flush(); 
			out.close(); 
		}else{
			out.write( " <script   language=javascript> alert( '添加图片展示新闻失败！ ');window.location.href= 'PicNewsServlet?action=manage'; </script> "); 
			out.flush(); 
			out.close(); 		    
			}

	    } catch (Exception e) {
	     e.printStackTrace();
	    }
	   }
	  }	

	
	




		
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
